/*
 * @Author: Suo-Yuheng syh15399227325@163.com
 * @Date: 2025-08-25 09:08:58
 * @LastEditors: Suo-Yuheng syh15399227325@163.com
 * @LastEditTime: 2025-08-25 11:52:05
 * @FilePath: /0825/sharemem/comm.hpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#ifndef __COMM_HPP__
#define __COMM_HPP__

#include<iostream>
#include<string>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<sys/types.h>
#include"log.hpp"
#include<cstring>
#include<sys/stat.h>

using namespace std;

const int size = 4098;  // 共享内存的大小一般建议 4096 整数倍、这里实际上给了 4 kb * 2
const string pathname = "/home/suo";
const int proj_id = 0x6666;
log llog;

key_t GetKey()
{
    key_t k = ftok(pathname.c_str(), proj_id);
    if(k < 0)
    {
        llog(Fatal, "ftok error: %s\n", strerror(errno)); // 把日志小组件拿进来
        exit(1);
    }
    llog(Info, "ftok success, key is 0x%x", k);
    return k;
}

// 封装  获取共享内存
int GetShareMemHelper(int flag)
{
    key_t k = GetKey();
    int shmid = shmget(k, size, flag);
    if(shmid < 0)
    {
        llog(Fatal, "creat share memory error: %s", strerror(errno));
        exit(2);
    }
    llog(Info, "creat share memory success, shmid is %d", shmid);
    return shmid;
}

int CreateShm()
{
    return GetShareMemHelper(IPC_CREAT | IPC_EXCL | 0666);
}

int GetShm()
{
    return GetShareMemHelper(IPC_CREAT);
}









#define FIFO_FILE "./myfifo"
#define MODE 0664

enum{
    FIFO_CREATE_ERR = 1,
    FIFO_DELETE_ERR,
    FIFO_OPEN_ERR,
};

class Init
{
public:
    Init()
    {
        // 创建信道 ?? 命名管道
        int n = mkfifo(FIFO_FILE, MODE);
        if(n == -1)
        {
            // printf("%d: %s\n", errno, strerror(errno));
            perror("mkfifo");
            exit(FIFO_CREATE_ERR);
        }
    }

    ~Init()
    {
        int m = unlink(FIFO_FILE);
        if(m == -1)
        {
            perror("unlink");
            exit(FIFO_DELETE_ERR);
        }
    }
};



#endif